import isFunction from "./isFunction";
import isFunctionComponent from "./isFunctionComponent";
import mountNativeElement from './mountNativeElement'
/**
 * 渲染组件
 * @param {*} virtualDOM 
 * @param {*} container 
 */
export default function mountComponent (virtualDOM, container, oldDOM) {
  let nextVirtualDOM = null
  let component = null
  // 通过判断 virtual DOM 是否有 render 属性
  // 判断组件是类组件还是函数组件
  if (isFunctionComponent(virtualDOM)) {
    // 函数组件
    nextVirtualDOM = buildFunctionComponent(virtualDOM)    
  } else {
    // 类组件
    nextVirtualDOM = buildClassComponent(virtualDOM)
    component = nextVirtualDOM.component
  }
  // 判断组件中是否有组件
  if (isFunction(nextVirtualDOM)) {
    mountComponent(nextVirtualDOM, container, oldDOM)
  } else {
    mountNativeElement(nextVirtualDOM, container, oldDOM)
  }  
  if (component) {
    component.componentDidMount()
    if (component.props && component.props.ref) {
      component.props.ref(component)
    }
  }
}

/**
 * 返回组件中的 Virtual DOM
 * @param {*} virtualDOM 
 * @returns 
 */
function buildFunctionComponent (virtualDOM) {
  // 传入 DOM 的属性值，如果没有 props 则传入空对象
  return virtualDOM.type(virtualDOM.props || {})
}

/**
 * 处理类组件函数
 * @param {*} virtualDOM 
 */
function buildClassComponent (virtualDOM) {
  // 创建 Virtual DOM 对象的实例并传入 props 属性对象
  const component = new virtualDOM.type(virtualDOM.props || {})
  const nextVirtualDOM = component.render()
  // 传递组件的示例对象
  nextVirtualDOM.component = component
  return nextVirtualDOM
}